package com.ge.med.cchelper.popup.actions;

import java.io.File;

import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.ge.med.cchelper.Constants;
import com.ge.med.cchelper.bean.CSession;
import com.ge.med.cchelper.bean.Host;
import com.ge.med.cchelper.popup.job.FetchDirJob;
import com.ge.med.cchelper.util.ReourceHelper;

public class ReceiveAction implements IObjectActionDelegate {
	private Shell shell;
	private String folderFullOSPath;


	
	public void run(IAction arg0) {

		ReourceHelper resource = ReourceHelper.getResource();
		IProject project = ReourceHelper.getProject();
		CSession session = resource.getSession(project.getName());
		if (session==null||session.getHost() == null) {
			MessageDialog.openError(shell, "Error",
					"Please login clearcase server!");
			return;
		}

		FetchDirJob fetch = new FetchDirJob("please wait,read directory",folderFullOSPath);
		fetch.schedule();

	}

	
	public void selectionChanged(IAction arg0, ISelection arg1) {
		if (arg1 != null && arg1 instanceof IStructuredSelection) {
			IStructuredSelection obj = (IStructuredSelection) arg1;
			Object objs = obj.getFirstElement();
			
			if (objs instanceof IFolder) {
				//arg0.setEnabled(false);
				IFolder folder = (IFolder)objs;
				IProject currentPro = folder.getProject();
				ReourceHelper.setProject(currentPro);
				String vobPath = currentPro.getFullPath().toOSString()+File.separator+Constants.VOB;
				String currentPath = folder.getFullPath().toOSString();
				
				if(!currentPath.startsWith(vobPath)){
					arg0.setEnabled(false);
				}else{
					if(currentPath.equals(vobPath)){
					   folderFullOSPath = null;
					}else{
						folderFullOSPath = currentPath;
					}
				}
				
			}else if (!( objs instanceof IProject)) {
				arg0.setEnabled(false);
			}else if(objs instanceof IProject){
				ReourceHelper.setProject((IProject)objs);
				folderFullOSPath =null;
				arg0.setEnabled(false);
			}
		}
	}

	
	public void setActivePart(IAction arg0, IWorkbenchPart arg1) {
		shell = arg1.getSite().getShell();
	}

	public static void main(String[] strs) {
		Host host = new Host();
		host.setIp("3.36.231.206");
		host.setUserid("chenxp");
		host.setPassword("cxp12cxp");
		ReceiveAction action = new ReceiveAction();
		action.run(null);

	}

}
